package com.klikmee.sms.core.base.communicator.starion;

import java.text.MessageFormat;

import org.apache.log4j.Logger;

import com.klikmee.sms.core.base.communicator.AbstractDeliveryReport2MessageResolver;
import com.klikmee.sms.core.base.communicator.DeliveryReport;
import com.klikmee.sms.core.base.exceptions.DeliveryReportNotResolvedException;
import com.klikmee.sms.core.commons.exceptions.ErrorInfo;
import com.klikmee.sms.core.model.OutgoingMessage;

public class StartionDeliveryReport2MessageResolverImpl extends AbstractDeliveryReport2MessageResolver {

	/**
	 * Logger instance
	 */
	private Logger logger = Logger.getLogger(StartionDeliveryReport2MessageResolverImpl.class);

	/**
	 * Resolves Starion delivery report to outgoint message sent via this provider.
	 * Resolution is done using {@link OutgoingMessage#getProvidersMesssageId()} value.
	 * @param deliveryReport object containing necessary data for delivery report resolution.
	 * 
	 * @return actual {@link OutgoingMessage} obj sent via Starion communicator.
	 * @throws DeliveryReportNotResolvedException in case that received delivery report could not be associated to outgoing message.
	 */
	@Override
	public OutgoingMessage resolve(DeliveryReport deliveryReport) throws DeliveryReportNotResolvedException {
		OutgoingMessage sentMessage = outgoingMessageDAO.findByProvidesMessageId(deliveryReport.getProvidersMessageId());
		// if outgoing message could not be found, throw an exception
		if (sentMessage == null) {
			DeliveryReportNotResolvedException exception = new DeliveryReportNotResolvedException("Could not resolve delivery report for starion provider");
			ErrorInfo errorInfo = exception.addInfo();
			errorInfo.getParameters().put("MessageId", deliveryReport.getMessageId());

			throw exception;
		}
		logger.info(MessageFormat.format("Resolved delivery report to outgoing message id [{0}]", sentMessage.getId()));
		return sentMessage;
	}

}
